package com.DosonLeung.homeschoolcommunication.Modules.SystemAlbumModule;

/**
 * Created by DosonLeung on 2014/10/22.
 */
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.DosonLeung.homeschoolcommunication.Components.GridAdapter;
import com.DosonLeung.homeschoolcommunication.R;
import com.DosonLeung.homeschoolcommunication.Utils.DialogUtil;

public class SystemAlbumActivity extends Activity
{
    Activity self = this;
    GridView gridView;
    TextView textView;
    // 记录当前的父文件夹
    File currentParent;
    // 记录当前路径下的所有文件的文件数组
    File[] currentFiles;
    //该是图的adapter
    GridAdapter gridAdapter;
    //该Activity的Handler
    final Handler sHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0x200){
                Bundle data = msg.getData();
                int index =data.getInt("index");
                try{
                    (gridAdapter.getImagesList().get(index)).setImageBitmap(gridAdapter.getBitmapsList().get(index));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.album);
        //获取列出全部文件的ListView
        gridView = (GridView) findViewById(R.id.album_grid);
        textView = (TextView) findViewById(R.id.album_path);
        //获取系统的SD卡的目录
        File root = new File("/storage/sdcard0/DCIM");
        //如果 SD卡存在
        if (root.exists())
        {
            currentParent = root;
            currentFiles = root.listFiles();
            //使用当前目录下的全部文件、文件夹来填充ListView
            inflateListView(currentFiles);
        }
        // 为ListView的列表项的单击事件绑定监听器
        gridView.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                // 用户单击了文件，直接返回，不做任何处理
                //if (currentFiles[position].isFile())
                //    return;
                // 获取用户点击的文件夹下的所有文件
                String suffix = ((currentFiles[position].getName()).substring(currentFiles[position].getName().lastIndexOf(".") + 1));
                if(suffix.equalsIgnoreCase("jpg")){
                    DialogUtil.showDialog(SystemAlbumActivity.this,SystemAlbumActivity.this,"选取该图片？",currentFiles[position].getPath());
                }else{
                    File[] tmp = currentFiles[position].listFiles();
                    if (tmp == null || tmp.length == 0 ) {
                        Toast.makeText(SystemAlbumActivity.this, "当前路径不可访问或该路径下没有文件",
                                Toast.LENGTH_LONG).show();
                    }else {
                        //获取用户单击的列表项对应的文件夹，设为当前的父文件夹
                        currentParent = currentFiles[position];
                        //保存当前的父文件夹内的全部文件和文件夹
                        currentFiles = tmp;
                        // 再次更新ListView
                        inflateListView(currentFiles);
                    }
                }
            }
        });

        // 获取上一级目录的按钮
        Button parent = (Button) findViewById(R.id.parent);
        parent.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View source)
            {
                self.finish();
            }
        });
    }

    //Dialog回调事件，选择了当前图片
    public void selectPicture(String url){
        Intent intent = getIntent();
        intent.putExtra("album",url);
        SystemAlbumActivity.this.setResult(RESULT_OK,intent);
        SystemAlbumActivity.this.finish();
    }

    private void inflateListView(File[] files)
    {
        // 创建一个List集合，List集合的元素是Map
        List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < files.length; i++){
            Map<String, Object> listItem = new HashMap<String, Object>();
            //获取文件后缀名
            String suffix = ((files[i].getName()).substring(files[i].getName().lastIndexOf(".")+1));
            //如果当前File是文件夹，使用folder图标；否则使用file图标
            if (files[i].isDirectory())
            {
                listItem.put("icon", R.drawable.folder);
            }
            else if(suffix.equalsIgnoreCase("jpg")){
                listItem.put("icon",files[i].getPath());
            }
            else
            {
                listItem.put("icon", R.drawable.file);
            }
            listItem.put("fileName", files[i].getName());
            //添加List项
            listItems.add(listItem);
        }
        // 创建一个SimpleAdapter
        gridAdapter = new GridAdapter(this, listItems,
                R.layout.album_item, new String[] { "icon", "fileName" }, new int[] {
                R.id.icon, R.id.file_name },sHandler);
        // 为ListView设置Adapter
        gridView.setAdapter(gridAdapter);
        try{
            textView.setText("当前路径为：" + currentParent.getCanonicalPath());
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}
